#include "Resources.h"

Resources* Resources::instance = 0;

Resources::Resources()
{}

Resources::~Resources()
{
	std::map<std::string, SDL_Texture*>::iterator itTexture = loadedTextures.begin();
	while (itTexture != loadedTextures.end())
	{
		SDL_DestroyTexture(itTexture->second);
		itTexture++;
	}
	loadedTextures.clear();

	std::map<std::string, TTF_Font*>::iterator itFont = loadedFonts.begin();
	while (itFont != loadedFonts.end())
	{
		TTF_CloseFont(itFont->second);
		itFont++;
	}
	loadedFonts.clear();
}

SDL_Texture* Resources::GetTexture(const std::string& path)
{
	if (loadedTextures[path] == nullptr)
	{
		loadedTextures[path] = LoadImage(path, Engine::GetInstance()->GetRenderer());
	}
	return loadedTextures[path];
}

TTF_Font* Resources::GetFont(const std::string& path, int size)
{
	std::stringstream ss;
	ss << path << "_" << size;
	if (loadedFonts[ss.str()] == nullptr)
	{
		loadedFonts[ss.str()] = LoadFont(path, size);
	}
	return loadedFonts[ss.str()];
}

SDL_Texture* Resources::LoadImage(const std::string& path, SDL_Renderer* renderer)
{
	SDL_Texture* loadedImage = IMG_LoadTexture(renderer, path.c_str());
	if (!loadedImage)
	{
		std::cout << "Failed to load image: " << path << " -- " << IMG_GetError();
	}
	return loadedImage;
}

TTF_Font* Resources::LoadFont(const std::string& path, int size)
{
	TTF_Font* loadedFont = TTF_OpenFont(path.c_str(), size);
	if (!loadedFont)
	{
		std::cout << "Failed to load font: " << path << " -- " << TTF_GetError();
	}
	return loadedFont;
}